package controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JTextField;

import models.ModelMyPlayer;

import org.ini4j.Ini;
import org.ini4j.Profile;

import others.ExecuteCommande;
import variables.VarConfigInt;

public class ActionCutListener implements ActionListener {

	protected ModelMyPlayer myPlayer;
	protected String src;
	protected String ffmpeg;
	protected Profile.Section path;
	protected JTextField startTF;
	protected JTextField durationTF;
	protected Ini configIni;

	public ActionCutListener(ModelMyPlayer myPlayer, JTextField startTF,
			JTextField durationTF, Ini configIni) {
		this.myPlayer = myPlayer;
		this.startTF = startTF;
		this.durationTF = durationTF;
		this.configIni = configIni;
	}

	public void actionPerformed(ActionEvent e) {
		// int time, duration;
		this.src = this.myPlayer.getSrc();
		this.ffmpeg = this.configIni.get(VarConfigInt.CONFIG_SECTION_SOFTWARE,
				VarConfigInt.CONFIG_VAR_SOFTWARE_FFMPEG);

		this.path = this.configIni.get("paths");
		File dir = new File((String) this.path.get("dest"));
		dir.mkdir();

		DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
		String fileName = dir.getAbsolutePath() + "/Capture-"
				+ df.format(new Date()) + ".avi";
//		new ExecuteCommande(ffmpeg + " -i " + src + " -ss "
//				+ startTF.getText() + " -to " + durationTF.getText()
//				+ " -vcodec copy -acodec copy -y " + fileName).run();
//		new ExecuteCommande(ffmpeg + " -i " + src + " -ss "
//				+ getTimeVideo(2210388) + " -to " + getTimeVideo(2470531)
//				+ " -vcodec copy -acodec copy -y " + fileName).run();
		new ExecuteCommande(ffmpeg + " -i " + src + " -ss "
				+ startTF.getText() + " -to " + durationTF.getText()
				+ " -c:v libx264 -c:a aac -strict -2 " + fileName).run();
//		new ExecuteCommande(ffmpeg + " -i " + src + " -ss "
//				+ startTF.getText() + " -to " + durationTF.getText()
//				+ " -vcodec copy -an " + fileName).run();
	}
	
	public String getTimeVideo(long value) {
		int seconds = (int) (value / 1000) % 60;
		int minutes = (int) ((value / (1000 * 60)) % 60);
		int hours = (int) ((value / (1000 * 60 * 60)) % 24);
		int milliseconds = (int) (value - ((hours * 1000 * 60 * 60) + (minutes * 1000 * 60) + (seconds * 1000)));
		return new String(hours + ":" + minutes + ":" + seconds + "." + milliseconds);
	}

}
